<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      class GameArea {
        constructor() {
          this.canvas = document.createElement("canvas");
          this.start();
          document.addEventListener("keydown", function (e) {
            this.key = e.keyCode;
          });
          document.addEventListener("keyup", function (e) {
            this.key = false;
          });
        }

        start() {
          this.canvas.width = 480;
          this.canvas.height = 270;
          this.canvas.style.border = "1px solid gray";
          this.canvas.style.backgroundColor = "lightgray";
          this.context = this.canvas.getContext("2d");
          document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        }

        clear() {
          this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
      }

      class GamePiece {
        constructor(width, height, color, x, y, ctx) {
          this.width = width;
          this.height = height;
          this.color = color;
          this.x = x;
          this.y = y;
          this.ctx = ctx;
          this.speedY = 0;
          this.speedX = 0;
          this.drawRect();
        }

        drawRect() {
          this.ctx.fillStyle = this.color;
          this.ctx.fillRect(this.x, this.y, this.width, this.height);
        }

        update() {
          console.log("更新");
          this.drawRect();
        }

        newPos() {
          this.x += this.speedX;
          this.y += this.speedY;
        }
      }

      let myGameArea, myGamePiece;
      function startGame() {
        myGameArea = new GameArea();
        myGamePiece = new GamePiece(30, 30, "red", 10, 120, myGameArea.context);

        // 设置定时器 0.02s 更新布局
        this.interval = setInterval(updateGameArea, 1000);
      }

      function updateGameArea() {
        // 清除画布
        myGameArea.clear();
        // 设置移速
        myg;
        myGamePiece.speedX += Math.random() * 2 - 1;
        myGamePiece.speedY += Math.random() * 2 - 1;
        myGamePiece.newPos();
        myGamePiece.update();
      }

      function stopMove() {
        myGamePiece.speedX = 0;
        myGameArea.speedY = 0;
      }

      startGame();
    </script>
  </body>
</html>
